package com.example.baiduapi.Chart.Picther;

import com.alibaba.fastjson.JSON;
import okhttp3.*;


import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

/*{"data":{"taskId":17897837},"log_id":1722463365846897749}*/
public class Sample {
    public static final String API_KEY = "0DoFzsnxMn2Wg0w6BEbkz8X5";
    public static final String SECRET_KEY = "iAmvy43H9gvL6n4jRCgL853vKsYDGkG3";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String []args) throws IOException{
        String getpicther = getpicther("森林", "1024*1024", "二次元");
        System.out.println(getpicther);
    }
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    /**
     * 请求生成图片
     * @param text 请求文本
     * @param size 生成的图片大小
     * @param style 生成的图片样式
     * @return 如果data不为空返回：{"taskId":17897837}否则返回:{log_id=1722523750333663797, error_msg=超过配额, error_code=4}
     * @throws IOException
     */
    public static String getpicther(String text,String size,String style) throws IOException {
        String result= null;
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"resolution\":\""+size+"\",\"style\":\""+style+"\",\"text\":\""+text+"\"}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ResponseBody responseBody = response.body();
        String json = responseBody.string();
        System.out.println(json);
        Map data = JSON.parseObject(json, Map.class);
        if(data.get("data")==null){
            /*result = data.get("log_id").toString()+","+data.get("error_msg").toString()+","+data.get("error_code").toString();*/
            result = data+"";
        }else{
            result = data.get("data")+"";
        }
        return result;
    }


    /**
     * 显示图片
     * @param taskId 图片地址唯一ID
     * @return 成功返回 {"data":{"style":"二次元","taskId":17897837,"imgUrls":[{"image":"https://wenxin.baidu.com/younger/file/ERNIE-ViLG/b370350891b2c8a4a1f3b73aa03128c4ex"}],"text":"竹子","status":1,"createTime":"2023-11-09 11:57:23","img":"https://wenxin.baidu.com/younger/file/ERNIE-ViLG/b370350891b2c8a4a1f3b73aa03128c4ex","waiting":"0"},"log_id":1722490078729413968}
     * @throws IOException
     */
     public static String shwoPic(String taskId) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n" +
                "    \"taskId\":\""+taskId+"\"\n" +
                "}");
        System.out.println(body);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        ResponseBody responseBody = response.body();
        String json = responseBody.string();
        System.out.println(json);
        com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(json);
//取出复杂对象中各项内容
        String dataz = jsonObj.getString("data");
        com.alibaba.fastjson.JSONObject jsonObj2 = JSON.parseObject(dataz.toString());
//取出复杂对象中各项内容
        System.out.print("图片地址："+dataz);
        String dataimg = jsonObj2.getString("img");
        System.out.print("图片地址："+dataimg);
        try {
            ImgLoader.load(dataimg.toString(),"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

}
